from flask import Flask, request, jsonify, session

app = Flask(__name__)
app.secret_key = 'secret'


@app.route('/')
def hello():
    return 'Hello World!'


@app.route('/hey/<username>')
def hey(username):
    return f'Hey {username}!'


# 只接受数字
@app.route('/number/<int:num>')
def number(num):
    return f'{num} is a number!'


# 一个POST方法
@app.route('/user/add', methods=['POST'])
def user_add():
    return 'User add!'


# 重定向
@app.route('/redirect')
def redirect():
    return app.redirect('https://www.baidu.com')


@app.route('/test/first/post', methods=['POST'])
def test_first_post():
    return 'test first post!'


# GET请求，通过查询字符串获取参数
@app.route('/test/query')
def test_get():
    username = request.args.get('username')
    return f'获取到用户名为：{username} 发来的请求'


# POST请求，通过请求体获取参数
@app.route('/test/post', methods=['POST'])
def test_post():
    # 注意这里获取到的是一个dict
    payload = request.get_json()
    username = payload.get('username')
    return jsonify({'code': 200, 'message': '请求成功', 'data': {'username': username}})


# 登录
@app.route('/session/login', methods=['POST'])
def login():
    # 帐号：root
    # 密码：abc123
    payload = request.get_json()
    username = payload.get('username')
    password = payload.get('password')
    # if username == None or password == None:
    #     return jsonify({'code': 400, 'message': '参数错误', 'data': {}})
    # 上面这段逻辑，可以用如下写法简化：
    if not all([username, password]):
        return jsonify({'code': 400, 'message': '参数错误', 'data': {}})
    
    if username == 'root' and password == 'abc123':
        session['username'] = username 
        session['token'] = 'root_token'
        return jsonify({'code': 200, 'message': '登录成功', 'data': {'token': 'root_token'}})
    else:
        return jsonify({'code': 400, 'message': '登录失败', 'data': {}})


# 登出
@app.route('/session/logout', methods=['GET'])
def logout():
    # 将session清空即可
    session.clear()
    return jsonify({'code': 200, 'message': '登出成功', 'data': {}})


# 检查登录状态
@app.route('/session/get', methods=['GET'])
def check_session():
    if 'username' in session and 'token' in session:
        return jsonify({'code': 200, 'message': '已登录', 'data': {'username': session['username'], 'token': session['token']}})
    else:
        return jsonify({'code': 400, 'message': '未登录', 'data': {}})


app.run(host='0.0.0.0', port=9000, debug=True)
